<template>
  <div class="admin-page admin-class">
    <div class="page-header">
      <h1>队次管理</h1>
      <div class="actions">
        <el-button type="primary" @click="openClassDialog(null)">
          <el-icon><Plus /></el-icon> 新增队次
        </el-button>
      </div>
    </div>
    
    <el-card class="table-card">
      <div class="filter-container">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="队次名称">
            <el-input v-model="filters.name" placeholder="请输入队次名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="队次状态">
            <el-select v-model="filters.statusId" placeholder="请选择状态" clearable style="width: 120px;">
              <el-option 
                v-for="status in statuses" 
                :key="status.id" 
                :label="status.name" 
                :value="status.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchClasses">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredClasses"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="队次ID" width="100" resizable></el-table-column>
        <el-table-column prop="name" label="队次名称" min-width="120" resizable></el-table-column>
        <el-table-column prop="departmentName" label="所属单位" min-width="120" resizable></el-table-column>
        <el-table-column prop="statusName" label="状态" min-width="100" resizable></el-table-column>
        <el-table-column label="操作" fixed="right" width="280" resizable>
          <template #default="scope">
            <el-button size="small" type="primary" @click="openClassDialog(scope.row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="warning" @click="openStatusDialog(scope.row)">
              <el-icon><Switch /></el-icon> 状态
            </el-button>
            <el-button size="small" type="danger" @click="deleteClass(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 队次编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑队次' : '新增队次'"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      @close="handleDialogClose"
    >
      <el-form :model="classForm" :rules="rules" ref="classFormRef" label-width="80px">
        <el-form-item label="队次名称" prop="name">
          <el-input v-model="classForm.name" placeholder="请输入队次名称"></el-input>
        </el-form-item>
        <el-form-item label="所属单位" prop="departmentId">
          <el-select v-model="classForm.departmentId" placeholder="请选择单位" filterable style="width: 100%;"
            @change="(val) => {
              const department = departments.find(dept => dept.id === val);
              if (department) {
                classForm.departmentName = department.name;
              }
            }">
            <el-option 
              v-for="dept in departments" 
              :key="dept.id" 
              :label="dept.name" 
              :value="dept.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="statusId">
          <el-select v-model="classForm.statusId" placeholder="请选择状态" style="width: 100%;"
            @change="(val) => {
              const status = statuses.find(s => s.id === val);
              if (status) {
                classForm.statusName = status.name;
              }
            }">
            <el-option 
              v-for="status in statuses" 
              :key="status.id" 
              :label="status.name" 
              :value="status.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitClassForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 状态修改对话框 -->
    <el-dialog
      title="修改队次状态"
      v-model="statusDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="statusFormRef" 
        :model="statusForm" 
        :rules="statusRules" 
        label-width="80px"
      >
        <el-form-item label="队次">
          <el-input :value="statusForm.className" readonly></el-input>
        </el-form-item>
        
        <el-form-item label="当前状态">
          <el-input :value="statusForm.currentStatusName" readonly></el-input>
        </el-form-item>
        
        <el-form-item label="新状态" prop="newStatusId">
          <el-select 
            v-model="statusForm.newStatusId" 
            placeholder="选择新状态" 
            style="width: 100%;"
          >
            <el-option 
              v-for="status in statuses" 
              :key="status.id" 
              :label="status.name" 
              :value="status.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStatusChange">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, reactive, nextTick } from "vue";
import { classApi } from "@/api/base-data";
import { departmentApi } from "@/api/base-data";
import { classStatusApi } from "@/api/base-data";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Switch } from "@element-plus/icons-vue";

export default {
  components: {
    Plus,
    Edit,
    Delete,
    Switch
  },
  setup() {
    const classes = ref([]);
    const departments = ref([]);
    const statuses = ref([]);
    const loading = ref(false);
    const submitting = ref(false);
    const dialogVisible = ref(false);
    const classFormRef = ref(null);
    
    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    
    // 筛选条件
    const filters = reactive({
      name: "",
      statusId: ""
    });
    
    // 班级表单
    const classForm = reactive({
      id: "",
      name: "",
      departmentId: "",
      departmentName: "",
      statusId: "",
      statusName: ""
    });
    
    // 强制重置表单的方法
    const forceResetClassForm = () => {
      classForm.id = "";
      classForm.name = "";
      classForm.departmentId = "";
      classForm.departmentName = "";
      classForm.statusId = "";
      classForm.statusName = "";
    };
    
    // 状态修改相关
    const statusDialogVisible = ref(false);
    const statusFormRef = ref(null);
    const statusForm = reactive({
      classId: null,
      className: '',
      currentStatusName: '',
      newStatusId: ''
    });
    
    // 状态修改表单验证规则
    const statusRules = {
      newStatusId: [
        { required: true, message: '请选择新状态', trigger: 'change' }
      ]
    };
    
    const isEdit = computed(() => !!classForm.id);
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: "请输入队次名称", trigger: "blur" }
      ],
      departmentId: [
        { required: true, message: "请选择所属单位", trigger: "change" }
      ],
      statusId: [
        { required: true, message: "请选择状态", trigger: "change" }
      ]
    };

    const fetchClasses = async () => {
      loading.value = true;
      try {
        classes.value = await classApi.getAllClasses();
        total.value = classes.value.length;
      } catch (error) {
        console.error("获取队次列表失败:", error);
        ElMessage.error("获取队次列表失败");
      } finally {
        loading.value = false;
      }
    };
    
    const fetchDepartments = async () => {
      try {
        departments.value = await departmentApi.getAllDepartments();
      } catch (error) {
        console.error("获取单位列表失败:", error);
        ElMessage.error("获取单位列表失败");
      }
    };
    
    const fetchStatuses = async () => {
      try {
        statuses.value = await classStatusApi.getAllClassStatuses();
      } catch (error) {
        console.error("获取状态列表失败:", error);
        ElMessage.error("获取状态列表失败");
      }
    };
    
    // 根据筛选条件过滤数据
    const filteredClasses = computed(() => {
      let filtered = classes.value;
      
      if (filters.name) {
        filtered = filtered.filter(cls => 
          cls.name.includes(filters.name)
        );
      }
      
      if (filters.statusId) {
        filtered = filtered.filter(cls => 
          cls.statusId === filters.statusId
        );
      }
      
      // 更新总数
      total.value = filtered.length;
      
      // 返回当前页的数据
      const startIndex = (currentPage.value - 1) * pageSize.value;
      return filtered.slice(startIndex, startIndex + pageSize.value);
    });
    
    // 搜索班级
    const searchClasses = () => {
      currentPage.value = 1;
    };
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.name = "";
      // 重置筛选条件后恢复默认筛选（在读状态）
      const inSchoolStatus = statuses.value.find(status => status.name === '在读');
      filters.statusId = inSchoolStatus ? inSchoolStatus.id : "";
      currentPage.value = 1;
    };
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };
    
    // 打开队次编辑对话框
    const openClassDialog = async (cls) => {
      // 先强制重置表单数据
      forceResetClassForm();
      
      if (cls) {
        // 编辑模式：填充现有数据
        classForm.id = cls.id;
        classForm.name = cls.name;
        classForm.departmentId = cls.departmentId;
        classForm.departmentName = cls.departmentName;
        classForm.statusId = cls.statusId;
        classForm.statusName = cls.statusName;
      } else {
        // 新增模式：设置默认值
        const inSchoolStatus = statuses.value.find(status => status.name === '在读');
        if (inSchoolStatus) {
          classForm.statusId = inSchoolStatus.id;
          classForm.statusName = inSchoolStatus.name;
        }
      }
      
      dialogVisible.value = true;
      
      // 使用 nextTick 确保对话框完全渲染后再清除验证状态
      await nextTick();
      if (classFormRef.value) {
        classFormRef.value.clearValidate();
      }
    };
    
    // 重置班级表单
    const resetClassForm = async () => {
      Object.assign(classForm, {
        id: "",
        name: "",
        departmentId: "",
        departmentName: "",
        statusId: "",
        statusName: ""
      });
      
      // 使用 nextTick 确保数据绑定完成后再重置表单验证
      await nextTick();
      if (classFormRef.value) {
        classFormRef.value.resetFields();
        classFormRef.value.clearValidate();
      }
    };
    
    // 提交队次表单
    const submitClassForm = async () => {
      if (!classFormRef.value) return;
      
      try {
        await classFormRef.value.validate();
        submitting.value = true;
        
        if (isEdit.value) {
          await classApi.updateClass(classForm.id, classForm);
          ElMessage.success("更新队次成功");
        } else {
          await classApi.createClass(classForm);
          ElMessage.success("创建队次成功");
        }
        
        dialogVisible.value = false;
        fetchClasses();
      } catch (error) {
        console.error("提交队次表单失败:", error);
        ElMessage.error("操作失败");
      } finally {
        submitting.value = false;
      }
    };

    // 删除队次
    const deleteClass = async (cls) => {
      try {
        await ElMessageBox.confirm(`确定要删除队次 ${cls.name} 吗？`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        
        await classApi.deleteClass(cls.id);
        ElMessage.success("删除成功");
        fetchClasses();
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除队次失败:", error);
          ElMessage.error(`删除队次失败: ${error.message || '未知错误'}`);
        }
      }
    };
    
    // 处理对话框关闭
    const handleDialogClose = async () => {
      // 对话框关闭时强制重置表单数据
      forceResetClassForm();
      
      // 使用 nextTick 确保数据绑定完成后再清除验证状态
      await nextTick();
      if (classFormRef.value) {
        classFormRef.value.clearValidate();
      }
    };

    // 打开状态修改对话框
    const openStatusDialog = (cls) => {
      const currentStatus = statuses.value.find(status => status.id === cls.statusId);
      
      statusForm.classId = cls.id;
      statusForm.className = cls.name;
      statusForm.currentStatusName = currentStatus ? currentStatus.name : '未知';
      statusForm.newStatusId = '';
      
      statusDialogVisible.value = true;
      
      // 在下一个事件循环中重置表单验证
      setTimeout(() => {
        statusFormRef.value && statusFormRef.value.clearValidate();
      }, 0);
    };
    
    // 提交状态修改
    const submitStatusChange = async () => {
      if (!statusFormRef.value) return;
      
      statusFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            await classApi.updateClassStatus(statusForm.classId, {
              statusId: statusForm.newStatusId
            });
            ElMessage.success('修改队次状态成功');
            
            // 关闭对话框并刷新数据
            statusDialogVisible.value = false;
            fetchClasses();
          } catch (error) {
            console.error('修改队次状态失败:', error);
            ElMessage.error(`修改队次状态失败: ${error.message || '未知错误'}`);
          }
        } else {
          ElMessage.warning('请正确填写表单内容');
          return false;
        }
      });
    };

    onMounted(async () => {
      await Promise.all([fetchClasses(), fetchDepartments(), fetchStatuses()]);
      
      // 初始化时默认只显示"在读"状态的队列
      const inSchoolStatus = statuses.value.find(status => status.name === '在读');
      if (inSchoolStatus) {
        filters.statusId = inSchoolStatus.id;
      }
    });

    return {
      classes,
      departments,
      statuses,
      filteredClasses,
      loading,
      filters,
      currentPage,
      pageSize,
      total,
      classForm,
      classFormRef,
      rules,
      dialogVisible,
      submitting,
      isEdit,
      searchClasses,
      resetFilters,
      handlePageChange,
      openClassDialog,
      submitClassForm,
      deleteClass,
      statusDialogVisible,
      statusFormRef,
      statusForm,
      statusRules,
      openStatusDialog,
      submitStatusChange,
      handleDialogClose,
      forceResetClassForm
    };
  }
};
</script>

<style scoped>
/* 特定于队次管理页面的样式可以放在这里 */
</style>
